package com.jky.trial.controller;

import com.alibaba.fastjson.JSONObject;
import com.jky.trial.common.BaseResult;
import com.jky.trial.common.DateUtil;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.Utils;
import com.jky.trial.common.poi.XlsUtil;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.entity.Category;
import com.jky.trial.entity.Project;
import com.jky.trial.service.CategoryService;
import com.jky.trial.service.ProjectService;
import com.jky.trial.service.RecordService;
import com.jky.trial.service.TaskService;
import com.jky.trial.vo.ProjectVo;
import com.jky.trial.vo.RecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/xls")
public class XlsController {

    private XlsUtil xlsUtil;
    private TaskService taskService;
    private RecordService recordService;
    private ProjectService projectService;
    CategoryService categoryService;

    @Autowired
    XlsController(XlsUtil xlsUtil,
                  CategoryService categoryService,
                  RecordService recordService,
                  ProjectService projectService, TaskService taskService) {
        this.recordService = recordService;
        this.xlsUtil = xlsUtil;
        this.categoryService = categoryService;
        this.taskService = taskService;
        this.projectService = projectService;
    }


    @GetMapping("/projectDetail")
    public OutputStream get(ProjectVo record, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            ListResult listResult = projectService.projectDetail(record);
            String title = "职责统计-" + DateUtil.dateToStr(new Date(), "yyyyMMdd");
            String fileName = Utils.processFileName(request, title + "Excel");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
            response.setCharacterEncoding("UTF-8");
            List<ProjectVo> list = (List<ProjectVo>) listResult.getList();
            List<Map> lm = new ArrayList();
            for (int i = 0; i < list.size(); i++) {
                Map map = new LinkedHashMap();
                ProjectVo vo = list.get(i);
                map.put("项目名称", vo.getName());
                map.put("项目编号", vo.getNo());
                map.put("项目状态", Integer.valueOf(1).equals(vo.getStatus()) ? "勘察中" : "已归档");
                map.put("项目负责人", record.getId().equals(vo.getDutyId()) ? "是" : "否");
                map.put("技术负责人", record.getId().equals(vo.getTechDirector()) ? "是" : "否");
                map.put("审核人", record.getId().equals(vo.getCheckId()) ? "是" : "否");
                map.put("审定人", record.getId().equals(vo.getApproveId()) ? "是" : "否");
                map.put("创建人", record.getId().equals(vo.getCreatorId()) ? "是" : "否");
                map.put("创建时间", DateUtil.dateToStr(vo.getCreateAt()));
                map.put("归档时间", Integer.valueOf(0).equals(vo.getStatus()) ? "未归档" : (vo.getArchiveAt() != null ? DateUtil.dateToStr(vo.getArchiveAt()) : ""));
                map.put("合同金额(W)", vo.getCash());
                map.put("是否创优", vo.getYou() == null ? "否" : (vo.getYou() ? "是" : "否"));
                lm.add(map);
            }

            response.setCharacterEncoding("UTF-8");
            return xlsUtil.writeContent(fileName, lm, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 明细导出
     *
     * @param map      数据 sheetName-list
     * @param fileName 导出文件名称
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/exportDetail/{fileName}")
    public OutputStream exportDetail(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            String title = fileName + DateUtil.dateToStr(new Date(), "yyyyMMdd");
            fileName = Utils.processFileName(request, title + "");

            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
            response.setCharacterEncoding("UTF-8");
            Category category = categoryService.detail(1);
            return xlsUtil.writeDetail(JSONObject.parseObject(category.getRemark2()), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @PostMapping("/saveExportDetail")
    public BaseResult saveExportDetail(@RequestBody Category category) {
        Category category1 = categoryService.detail(1);

        if (category1 == null) {
            category.setId(1);
            categoryService.save(category);
        } else {
            category.setId(1);
            categoryService.update(category);
        }
        return new BaseResult(true, "", 200);
    }

    @GetMapping("/dt/{projectId}/{type}")
    public OutputStream record(@PathVariable Integer projectId, @PathVariable Integer type, String typeLabel, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/plain");
        RecordVo recordVo = new RecordVo();
        recordVo.setProjectId(projectId);
        Project projectVo = projectService.detail(projectId);
        if (typeLabel == null) {
            typeLabel = "DT";
        }
        recordVo.setType(type);
        recordVo.setSize(Integer.MAX_VALUE);
        List<RecordVo> list = recordService.listWithTask(recordVo);
        String title = projectVo.getName() + "_" + DateUtil.dateToStr(new Date(), "yyyyMMdd");
        String fileName = Utils.processFileName(request, typeLabel + "_" + title + "");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".txt");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        return xlsUtil.exportTxt(response, getData(list, typeLabel).toString());
    }

    StringBuffer getData(List<RecordVo> list, String typeLabel) {
        StringBuffer stringBuffer = new StringBuffer();
        RecordVo vo = null;
        if (typeLabel.endsWith("DT")) {
            stringBuffer.append("钻孔编号,动探深度,动探实测锤击数\r\n");
        } else if (typeLabel.endsWith("BG")) {
            stringBuffer.append("钻孔编号,标贯深度,标贯实测锤击数\r\n");
        } else if (typeLabel.endsWith("ZK")) {
            stringBuffer.append("勘探点编号,层底深度,地层名称,地层颜色\r\n");
        } else if (typeLabel.endsWith("YTKC")) {
            stringBuffer.append("钻孔编号,初见水位,稳定水位,开孔日期,终孔日期\r\n");
        }
        if (typeLabel.endsWith("ZK")) {
            Map<String, List<RecordVo>> map = list.stream().collect(Collectors.groupingBy(RecordVo::getTNo));

            Iterator<String> iterator = map.keySet().iterator();
            ArrayList<RecordVo> list2 = new ArrayList<RecordVo>();
            for (; iterator.hasNext(); ) {
                String key = iterator.next();
                List<RecordVo> list1 = map.get(key);
                list1 = list1.stream().sorted((u1, u2) -> Float.valueOf(u1.getStartAt()).compareTo(Float.parseFloat(u2.getStartAt()))).collect(Collectors.toList());
                RecordVo current = null;
                for (int i = 0; i < list1.size(); i++) {
                    if (current != null) {
                        JSONObject jsonObject = JSONObject.parseObject(current.getMethod3());
                        JSONObject jsonObject2 = JSONObject.parseObject(list1.get(i).getMethod3());
                        if (
                                current.getEndAt().equals(list1.get(i).getStartAt())
                                        && jsonObject2.getString("remark21")
                                        .equals(jsonObject.getString("remark21"))
                        ) {//环节链接
                            if ((i + 1) >= list1.size()) { //尾环节判断
                                list2.add(list1.get(i));
                                //current = null;
                            } else {// 通环节过度
                                //list2.add(list1.get(i - 1));
                                current = list1.get(i);
                            }
                        } else { //新环节
                            if ((i + 1) >= list1.size()) {//尾环节判断
                                list2.add(list1.get(i - 1));//增加倒数第二环节
                                list2.add(list1.get(i));//增加倒数第一环节
                            } else {
                                list2.add(list1.get(i - 1));
                            }
                            //新环节过度
                            current = list1.get(i);
                        }
                    } else {//单个
                        if ((i + 1) >= list1.size()) { //
                            list2.add(list1.get(i));
                        } else {
                            current = list1.get(i);
                        }
                    }
                }
            }
            list = list2.stream().sorted((u1, u2) -> u1.getTNo().compareTo(u2.getTNo())).collect(Collectors.toList());

        }
        for (int i = 0; i < list.size(); i++) {
            vo = list.get(i);
            if (typeLabel.endsWith("YTKC")) {
                JSONObject itemObj = JSONObject.parseObject(vo.getMethod3());
                if (vo.getType().equals(DataStatus.LOG_SUB_TYPE_RECORD_SHUIWEI.getVal())) {
                    String holeAt =recordService.holeStartEnd(vo.getTargetId());///
                    stringBuffer.append(vo.getTNo() + ",");
                    stringBuffer.append(itemObj.getString("method2") + ",");
                    stringBuffer.append(itemObj.getString("method4") + ",");
                    stringBuffer.append(holeAt.split(",")[0] + ",");
                    stringBuffer.append(holeAt.split(",")[1] + "\n");
                }
            } else if (typeLabel.endsWith("DT")) {
                JSONObject itemObj = JSONObject.parseObject(vo.getMethod3());
                float start = Float.parseFloat(vo.getStartAt());
                float end = Float.parseFloat(vo.getEndAt());
                for (float k = start, j = 0; k < end; j++) {
                    String t = itemObj.getString("remark1" + ((int) j));
                    DecimalFormat df1 = new DecimalFormat("0.00");
                    String str = df1.format(k);
                    stringBuffer.append(vo.getTNo() + ",");
                    stringBuffer.append(str + ",");
                    stringBuffer.append((t == null ? "0" : t) + "\r\n");
                    k = Float.parseFloat(df1.format(BigDecimal.valueOf(k).add(BigDecimal.valueOf(0.1)).floatValue()));
                }
            } else if (typeLabel.endsWith("BG")) {
                JSONObject itemObj = JSONObject.parseObject(vo.getMethod3());
                int total = 0;
                for (int j = 1; j < 4; j++) {
                    total += Integer.valueOf(itemObj.getString("t" + j + "2")).intValue();
                }
                stringBuffer.append(vo.getTNo().toString() + ",");
                stringBuffer.append(itemObj.getString("t10") + ",");
                stringBuffer.append(total + "\r\n");

            } else if (typeLabel.endsWith("ZK")) {
                JSONObject itemObj = JSONObject.parseObject(vo.getMethod3());
                stringBuffer.append(vo.getTNo() + ",");
                stringBuffer.append(vo.getEndAt() + ",");
                stringBuffer.append(itemObj.getString("remark21") + ",");
                stringBuffer.append(itemObj.getString("method31") + "\r\n");
            }
        }
        return stringBuffer;
    }

    @GetMapping("/bg/{projectId}/{type}")
    public OutputStream bg(@PathVariable Integer projectId, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) {
        return record(projectId, type, "BG", request, response);
    }

    @GetMapping("/dc/{projectId}/{type}")
    public OutputStream dc(@PathVariable Integer projectId, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) {
        return record(projectId, type, "ZK", request, response);
    }

    @GetMapping("/ytkc/{projectId}/{type}")
    public OutputStream ytkc(@PathVariable Integer projectId, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) {
        return record(projectId, type, "YTKC", request, response);
    }

}
